package me.keiwu.task.controller;

import com.alibaba.fastjson.JSONObject;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.pub.util.ContextUtil;
import me.keiwu.task.rpc.UserRpc;
import me.keiwu.task.service.DonateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by kei on 19/12/2017.
 */
@RestController
@RequestMapping("/donate")
public class DonateController {

    @Autowired
    private DonateService donateService;
    @Autowired
    private UserRpc userRpc;
    @Autowired
    private CacheUtil cacheUtil;

    @RequestMapping("/step")
    public ResponseV2 donateStep(HttpServletRequest request, Integer step) {
        Long userId = ContextUtil.getLoginUserId(request);
        Integer userStep = userRpc.getUserStepsDaily(userId);
        if (userStep < step) return ResponseV2.fail("捐赠数量不正确");
        donateService.donateStep(userId, step);
        JSONObject json = new JSONObject();
        json.put("totalSteps", cacheUtil.getTotalDonateSteps());
        json.put("totalUsers", cacheUtil.getTotalDonateUsers());
        json.put("userDonate", cacheUtil.getUserDonateSteps(userId));
        return ResponseV2.ok(json);
    }

    @RequestMapping("/data")
    public ResponseV2 donateData(HttpServletRequest request) {
        Long userId = ContextUtil.getLoginUserId(request);
        JSONObject json = new JSONObject();
        json.put("userDonate", cacheUtil.getUserDonateSteps(userId));
        json.put("totalSteps", cacheUtil.getTotalDonateSteps());
        json.put("totalUsers", cacheUtil.getTotalDonateUsers());
        return ResponseV2.ok(json);
    }

}
